package com.example.demo.controller;

import com.example.demo.dao.DepartmentMapper;
import com.example.demo.dao.EmpolyeeMapper;
import com.example.demo.dao.LogMapper;
import com.example.demo.dto.Department;
import com.example.demo.dto.Empoyee;
import com.example.demo.dto.Log;
import com.example.demo.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/***
 * 静态资源接口
 */
@Controller
public class WebController {

    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    EmpolyeeMapper empolyeeMapper;
    @Autowired
    LogMapper logMapper;

//    HttpSession session
    @RequestMapping("/index")
    public String index(Model model) {
        Collection<Empoyee> empoyees = empolyeeMapper.getEmpoleeData();
        Collection<Department> departments = departmentMapper.getDepartmentDataList();

        model.addAttribute("empoyees", empoyees);
        model.addAttribute("departments", departments);

        model.addAttribute("logs", logMapper.getLogData());

        return "index";
    }

    @GetMapping("/deldep/{id}")
    public String deldep(@PathVariable("id") Integer id) {
        departmentMapper.deleteById(id);
        return "redirect:/index";
    }

    @GetMapping("/delemp/{id}")
    public String del(@PathVariable("id") Integer id) {
        empolyeeMapper.deleteById(id);
        return "redirect:/index";
    }

    @PostMapping("/addEmp")
    public String addEmp(@RequestBody Empoyee empoyee, HttpServletResponse resp) throws IOException {
        String result = empolyeeMapper.insert(empoyee);
        handelHttp(result, resp);
        return null;
    }

    @PostMapping("/addDep")
    public String addDep(@RequestBody Department department, HttpServletResponse resp) throws IOException {
        String result = departmentMapper.insert(department);
        handelHttp(result, resp);
        return null;
    }

    private void handelHttp(String result, HttpServletResponse resp) throws IOException {
        String hintMessage="success";
        if (!result.equals("操作成功")) {
            hintMessage = "error";
        }
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().println(hintMessage);
        resp.getWriter().close();
    }

}
